package com.coder520.foregroundservicetest;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

/**
 * Created by huang on 2017/7/11.
 */

public class CoundownService extends IntentService {
    public static final String ACTION_COUNT_DOWN = "com.coder520.foregroundservicetest_COUNDOWN";
    public static final String ACTION_STOP = "com.coder520.foregroundservicetest_STOP";
    private static final String TAG = CoundownService.class.getSimpleName();
    private int mCount = 1000;
    private boolean mStop = false;
    private Object mLock = new Object();

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     */
    public CoundownService() {
        super("countdown Service");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (intent == null || TextUtils.isEmpty(intent.getAction())) {
            return;
        }
        switch (intent.getAction()) {
            case ACTION_COUNT_DOWN:
                synchronized (mLock) {
                    while (!mStop) {
                        Log.d(TAG, "coder520 ..... mCount = " + mCount--);
                        try {
                            mLock.wait(1000);
                            if (mCount == 990) {
                                break;
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                break;
            case ACTION_STOP:
                synchronized (mLock) {
                    mStop = true;
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "coder520 ..... onDestroy called");
        super.onDestroy();

    }
}
